<route lang="yaml">
meta:
  requiresAuth: false
</route>

<template>
  <el-container>
    <el-header><Header></Header></el-header>
    <el-main>
      <!-- 商品卡片 -->
      <el-card class="goodCard">
        <div class="goodimg">
          <div class="showarea">
            <img
              :src="defaulturl ? baseimgurl + defaulturl : testurl"
              alt="加载失败"
            />
          </div>
          <div class="suoluetu">
            <ul>
              <li v-for="item in imgurl" :key="item.id">
                <img
                  :src="baseimgurl + item.path"
                  alt="加载失败"
                  @click="showimg(item.id)"
                />
              </li>
            </ul>
          </div>
        </div>
        <div class="goodinfo">
          <div class="publisher">
            <!-- <i class="iconfont icon-xiaoxi" style="color: #999;font-size: 20px;"></i> -->
            <img
              :src="
                itemData.user.profile.avatar
                  ? baseimgurl + itemData.user.profile.avatar
                  : testurl
              "
              alt="头像加载失败"
            />
            <span>{{ itemData.user.profile.nickname }}</span>
          </div>
          <div class="goodname">
            <span>{{ itemData.name }}</span>
          </div>
          <div class="description">
            <i
              class="iconfont icon-xiaoxi"
              style="color: #999; font-size: 20px"
            ></i
            >{{ itemData.description }}
          </div>
          <div>
            <i
              class="iconfont icon-ios-pricetags"
              style="color: #999; font-size: 20px"
            ></i>
            <el-tag>正品</el-tag>
            <el-tag>保险</el-tag>
            <el-tag>真货</el-tag>
            <el-tag>免邮</el-tag>
          </div>
          <div>
            <i
              class="iconfont icon-weizhi"
              style="color: #999; font-size: 20px"
            ></i>
            <span>{{ itemData.status }}</span>
          </div>
          <div class="time">
            <i
              class="iconfont icon-time"
              style="color: #999; font-size: 20px"
            ></i>
            <span>发布于</span
            ><span class="publishtime"
              ><strong>{{ itemData.createdAt }}</strong></span
            >
          </div>
          <div class="price">
            <i
              class="iconfont icon-wenjianxinxi"
              style="color: #999; font-size: 20px"
            ></i>
            <span class="nowprice">价格:{{ itemData.price }}元</span>
            <del class="oprice">原价:{{ itemData.originalPrice }}元</del>
          </div>
          <div class="operate">
            <!-- <el-button plain>添加到购物车</el-button> -->
            <!-- 编辑图片 -->

            <el-button plain @click="popAddphotosForm" v-show="canOperate"
              >编辑商品图片</el-button
            >
            <!-- 实现发布者修改商品信息功能 -->
            <el-button @click="popEditorForm" v-show="canOperate"
              >编辑商品</el-button
            >
            <el-button plain @click="buyItemForm" v-show="!canOperate&&(itemData.status==='AVAILABLE')">购买</el-button>
          </div>
        </div>

        <el-dialog v-model="buyItemFormVisible" title="购买">
          <el-form>
            选择地址:
            <el-radio v-model="Addresscos" :label="item.id" size="large" v-for="item in Address" :key="item.id" style="display: block;">{{item.address}}</el-radio>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="buy">确认购买</el-button>
              <el-button @click="buyItemFormVisible=false">返回</el-button>
            </span>
          </template>
        </el-dialog>

        <el-dialog v-model="editdialogVisible" title="商品信息修改">
          <el-form size="mini" label-width="120px">
            <el-form-item label="商品名字">
              <el-input v-model="editorForm.name"></el-input>
            </el-form-item>
            <el-form-item label="商品描述">
              <el-input v-model="editorForm.description"></el-input>
            </el-form-item>
            <el-form-item label="价格">
              <el-input
                type="number"
                v-model.number="editorForm.price"
              ></el-input>
            </el-form-item>
            <el-form-item label="原价">
              <el-input
                type="number"
                v-model.number="editorForm.originalPrice"
              ></el-input>
            </el-form-item>
            <!-- <el-form-item label="商品状态">
              <el-input v-model="editorForm.status"></el-input>
            </el-form-item> -->
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="editdialogVisible = false">取消</el-button>
              <el-button type="primary" @click="itemEditor">上传</el-button>
            </span>
          </template>
        </el-dialog>
        <el-dialog v-model="addPhotosdialogVisible" title="图片信息修改">
          <Photolist :a="imgurl" :Itemid="props.id"></Photolist>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="backItem">返回</el-button>
            </span>
          </template>
        </el-dialog>
      </el-card>

      <!-- 评论区卡片 -->
      <el-card class="commitCard">
        <!-- 评论实例 -->
        <div class="commenttitle">
          商品评价:
          <el-button type="primary" @click="commitDialogVisible = true"
            >发表信息</el-button
          >
        </div>

        <div class="commitbody" v-for="item in commitList" :key="item.id">
          <div class="commituser">
            <div class="avatar">
              <img :src="item.user.profile.avatar ?baseimgurl + item.user.profile.avatar:testurl" alt="头像加载失败" />
            </div>
            <div class="username">
              <span class="name">{{ item.user.profile.nickname }}</span>
              <span class="committime">{{ item.createdAt }}</span>
            </div>
          </div>

          <div class="committext">
            <div class="star">
              <i class="iconfont icon-xingxing1"></i>
              <i class="iconfont icon-xingxing1"></i>
              <i class="iconfont icon-xingxing1"></i>
              <i class="iconfont icon-xingxing1"></i>
              <i class="iconfont icon-xingxing"></i>
            </div>
            <div class="text">{{ item.content }}</div>
          </div>
        </div>
        <el-dialog v-model="commitDialogVisible" title="发布信息" width="30%">
          <textarea
            name=""
            id=""
            cols="40"
            rows="10"
            v-model="content.content"
            style="resize: none"
          ></textarea>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="commitDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="publish">发送</el-button>
            </span>
          </template>
        </el-dialog>
      </el-card>
    </el-main>
    <el-footer><Footer></Footer></el-footer>
  </el-container>
</template>

<script setup lang="ts">
import Photolist from '../../components/photolist.vue'
import Footer from '../../components/footer.vue'
import Header from '../../components/header.vue'
import { onMounted, ref, computed, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from '../../store'
import { useErrors } from '../../composable/useErrors'
import { Role } from '../../services/auth'
import {
  deleteItemById,
  getItemById,
  Item,
  ItemStatus,
  patchItemById,
  NewItemForm,
  publishCommit,
  getAllCommit,
  Commit
} from '../../services/items'
import { getAddress ,createNeworder} from '../../services/auth'
import '../../assets/css/icon/cykicon/iconfont.css'

/***
 * 钩子函数
 */
const commitList = ref<Commit[]>([])
onMounted(async () => {
  try {
    itemData.value = (await getItemById(props.id)).data
    commitList.value = (await getAllCommit(props.id)).data
    //初始化图片list和默认大图的路劲
    imgurl.value = itemData.value.photos
    //没有图片则默认大图为空，自动转到默认为list[0]的图片
    defaulturl.value = itemData.value.photos[0]?.path
      ? itemData.value.photos[0].path
      : ''
  } catch (err) {
    errorHandler(err)
  }
})

/**
 * 测试的东西
 */
//失踪图的url
const testurl =
  'https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png'

/**
 * 定义的一些工具方法，异常处理仓库(store,router,error,props)
 */
const props = defineProps<{ id: string }>()
const { errors, errorHandler } = useErrors()
const store = useStore()
const router = useRouter()
const baseimgurl = 'http://159.75.101.15:3000/'

/**
 * 响应式数据
 */
//是否能修改该商品，用计算属性
const canOperate = computed(
  () =>
    itemData.value?.user.id === store.state.currentUser?.id ||
    store.state.currentUser?.roles.includes(Role.ADMIN)
)
//修改商品文字信息表单，响应式数据
const editorForm = reactive<NewItemForm>({
  name: '',
  description: '',
  // 默认为未成交状态
  status: ItemStatus.AVAILABLE,
  price: 0,
  originalPrice: 0
})
// 保存商品数据的响应式变量，用于呈现页面
const itemData = ref<Item>({
  id: '',
  name: '',
  description: '',
  status: ItemStatus.DRAFT,
  price: 0,
  originalPrice: 0,
  updatedAt: new Date(),
  createdAt: new Date(),
  user: {
    id: '',
    profile: {
      id: '',
      nickname: '',
      avatar: '',
      gender: ''
    }
  },
  photos: []
})
//图片的默认路径，用于大图显示，为string的path
const defaulturl = ref<string>('')
//图片list，包括id,order,path
const imgurl = ref<{ id: string; path: string; order: number }[]>([])
//控制商品文本修改表单显示
const editdialogVisible = ref<boolean>(false)
//控制商品图片修改表单显示
const addPhotosdialogVisible = ref<boolean>(false)
/**
 * 提交修改文本信息的方法
 */
//编辑商品按钮的逻辑实现表单的显示
const popEditorForm = function () {
  editorForm.description=itemData.value.description
  editorForm.name=itemData.value.name
  editorForm.originalPrice = itemData.value.originalPrice
  editorForm.price = itemData.value.price
  editdialogVisible.value = true
}
//editdialog提交的逻辑
const itemEditor = async function () {
  try {
    itemData.value = (await patchItemById(itemData.value.id, editorForm)).data
    editdialogVisible.value = false
  } catch (err) {
    errorHandler(err)
  }
}

/**
 * 显示图片信息
 * 提交修改商品图片信息的方法
 */
//修改浏览区图片的path
function showimg(id: String) {
  const { path: a } = imgurl.value.filter((obj: { id: String }) => {
    return obj.id == id
  })[0]
  defaulturl.value = a
}
//控制编辑图片的表单的显示
const popAddphotosForm = () => (addPhotosdialogVisible.value = true)

async function backItem() {
  itemData.value = (await getItemById(props.id)).data
  commitList.value = (await getAllCommit(props.id)).data
  //初始化图片list和默认大图的路劲
  imgurl.value = itemData.value.photos
  //没有图片则默认大图为空，自动转到默认为list[0]的图片
  defaulturl.value = itemData.value.photos[0]?.path
    ? itemData.value.photos[0].path
    : ''
  addPhotosdialogVisible.value = false
}

/**
 * 评论
 */
let commitDialogVisible = ref<boolean>(false)
const content = ref<{ content: string }>({ content: '' })
async function publish() {
  ;(await publishCommit(props.id, content.value)).data
  commitList.value = (await getAllCommit(props.id)).data
  content.value.content = ''
  commitDialogVisible.value = false
}

/**
 * 购买生成订单
 */
let Address = ref()
let Addresscos = ref()
async function buyItemForm() {
  Address.value = (await getAddress()).data
  Addresscos.value=Address.value[0].id
  buyItemFormVisible.value = true
  console.log(Address.value)
}
async function buy() {
  const result = (await createNeworder({itemId:itemData.value.id,addressId:Addresscos.value})).data
  buyItemFormVisible.value = false
  itemData.value = (await getItemById(props.id)).data
  console.log(result)
}
const buyItemFormVisible = ref<boolean>(false)
</script>







<style lang="less" scoped>
.icon-xingxing1 {
  color: #f5a623;
}
.el-header {
  padding: 0;
  background-color: white;
  position: relative;
  z-index: 999;
  box-shadow: 0px -5px 10px #1a1919;
}
.el-footer {
  padding: 0;
}
.el-main {
  overflow: inherit;
  .el-card {
    margin: 30px auto;
    width: 1000px;
    height: auto;
    box-shadow: 0px -5px 10px #b8b4b4;
  }
  .goodimg {
    float: left;
    width: 40%;
    height: 100%;
    .showarea {
      width: 350px;
      height: 350px;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .suoluetu {
      height: 60px;
      margin-top: 15px;
      ul {
        display: inline;
        padding-inline-start: 0;
        li {
          list-style-type: none;
          float: left;
          width: 57px;
          height: 55px;
          margin-right: 10px;
          img {
            width: 55px;
            height: 55px;
          }
        }
      }
    }
  }
  .goodinfo {
    float: left;
    width: 40%;
    height: auto;
    div {
      margin-bottom: 20px;
    }
    .description {
      color: rgb(196, 189, 189);
    }
    .goodname {
      font-weight: bolder;
    }
    .time {
      .publishtime {
        color: rgb(55, 66, 219);
      }
    }
    .price {
      .nowprice {
        color: black;
      }
      .oprice {
        color: rgb(228, 11, 11);
      }
    }
    .publisher {
      position: relative;
      span {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        margin-left: 5px;
      }
      img {
        width: 50px;
        height: 50px;
        border-radius: 50%;
      }
    }

    span {
      margin-right: 15px;
    }
    i {
      margin-left: 5px;
      margin-right: 10px;
    }
    .operate {
      padding-top: 20px;
      text-align: center;
    }
  }
  .commitCard {
    text-align: center;
    .commenttitle {
      display: flex;
      justify-content: space-between;
    }
    .goodAndBad {
      text-align: left;
    }
    .commitbody {
      text-align: left;
      overflow: hidden;
      padding: 25px;
      border-bottom: 1px solid rgb(190, 187, 187);
      .commituser {
        float: left;
        overflow: hidden;
        .avatar {
          float: left;
          height: 50px;
          width: 50px;
          img {
            width: 50px;
            height: 50px;
            border-radius: 50%;
          }
        }
        .username {
          float: left;
          .name {
            display: block;
            margin-left: 5px;
            font-weight: bold;
          }
          .committime {
            display: block;
            margin-left: 5px;
            margin-top: 10px;
            font-size: 12px;
          }
        }
      }
      .committext {
        float: left;
        margin-left: 30px;
        .star {
        }
        .text {
          margin-top: 5px;
        }
      }
    }
  }
}
</style>
